package org.byqh.dqeai.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ConfigFilePostProcessor implements EnvironmentPostProcessor {

    private static final Map<String, String> PROPERTY_MAPPING = new HashMap<>();

    static {
        PROPERTY_MAPPING.put("upload.path", "upload.path");
        PROPERTY_MAPPING.put("server.port", "server.port");
        PROPERTY_MAPPING.put("spring.datasource.driver-class-name", "spring.datasource.druid.default.driver-class-name");
        PROPERTY_MAPPING.put("spring.datasource.jdbc-url", "spring.datasource.druid.default.url");
        PROPERTY_MAPPING.put("spring.datasource.username", "spring.datasource.druid.default.username");
        PROPERTY_MAPPING.put("spring.datasource.password", "spring.datasource.druid.default.password");
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String externalConfigPath = "./dqeai.properties"; // 或通过系统参数动态获取
        Resource resource = new FileSystemResource(externalConfigPath);

        if (resource.exists()) {
            try {
                Properties externalProps = new Properties();
                externalProps.load(resource.getInputStream());

                // 将外部属性按映射关系转换
                Properties springProps = new Properties();
                externalProps.forEach((keyObj, value) -> {
                    String externalKey = (String) keyObj;
                    String springKey = PROPERTY_MAPPING.get(externalKey);
                    if (springKey != null) {
                        springProps.put(springKey, value);
                    }
                });

                // 将转换后的属性注入环境变量（优先级最高）
                environment.getPropertySources().addFirst(
                        new PropertiesPropertySource("externalMappedConfig", springProps)
                );
            } catch (IOException e) {
                System.out.println("加载外部配置文件失败: " + externalConfigPath + "\n" + e.getMessage());
            }
        } else {
            System.out.println("未找到外部配置文件: " + externalConfigPath);
        }
    }
}
